<script setup lang="ts">
import {useFetchList} from "@/hooks/table/useFetchList";
import {
  addDataSource,
  deleteDataSource,
  editDataSource, getDataSourceContactPageList,
  getDataSourceDetail,
  getDataSourcePageList
} from "@/apis/callTaskConfigure/dataSource";
import {message} from "ant-design-vue";
import {queryOptions} from "@/views/callTaskConfigure/DataSource/consts/queryOptions";
import {DeleteOutlined, FormOutlined, PlusOutlined} from "@ant-design/icons-vue";
import {columns} from "@/views/callTaskConfigure/DataSource/consts/tableColumns";
import {getDataFieldList} from "@/apis/callTaskConfigure/dataField";
import {watch} from "vue";

const drawTitle = ref<string>('新增数据源')
const open = ref<boolean>(false)
const formRef = ref()
const dataFieldOptions = ref<any[]>([]);
const query = reactive({
  fieldName: '',
  fieldType: undefined,
  required: undefined,
})
const {tableData, handleSearch, handleTableChange, pagination, loading, initTable} = useFetchList(
    getDataSourcePageList,
    query
)
onMounted(() => {
  handleSearch()
})

let formState = reactive({
  name: '',
  remark: '',
  fieldIdList: [],
  id: ''
})

const rules = reactive({
  name: [{required: true, message: '请输入数据源名称', trigger: 'blur'}],
})

const handleAdd = () => {
  drawTitle.value = '新增数据源'
  formState = reactive({
    name: '',
    remark: '',
    fieldIdList: [],
    id: ''
  })
  open.value = true
}
const handleDelete = async (id: any) => {
  const res = await deleteDataSource({id: id})
  if (res.code === 200) {
    message.success('删除成功')
    handleSearch()
    return
  }
  message.error('删除失败')
}
const handleEdit = async (record: any) => {
  const res = await getDataSourceDetail({id: record.id})
  if (res.code === 200) {
    drawTitle.value = '编辑数据源'
    formState = reactive({...res.data})
    formState.fieldIdList = res.data.fieldList.map((item: any) => item.id)
    open.value = true
    return
  }
}

const handleSubmit = () => {
  formRef.value
      .validate()
      .then(async () => {
        const fn = formState.id ? editDataSource : addDataSource
        const res = await fn({
          ...formState
        })
        if (res.code === 200) {
          message.success('操作成功！')
          closeDrawer()
          formState.id ? handleSearch() : initTable()
          return
        }
        message.error('操作失败！')
      })
      .cache((error: any) => {
        console.log('error', error)
      })
}
const closeDrawer = () => {
  open.value = false
  formRef.value.resetFields()
  formState = reactive({
    name: '',
    remark: '0',
    fieldIdList: [],
    id: ''
  })
}
const fetchDataFields = async () => {
  try {
    const res = await getDataFieldList({});
    dataFieldOptions.value = res.data.map((item: any) => ({
      label: item.fieldName,
      value: item.id
    }));
  } catch (error) {
    console.error('获取数据字段列表失败:', error);
    message.error('获取数据字段列表失败');
    dataFieldOptions.value = [];
  }
}
watch(open, (value) => {
  if (value){
    fetchDataFields()
  }
})
</script>
<template>
  <div class="base-table-container">
    <BaseQuery :query-options="queryOptions" :query="query" class="mb8" @search="handleSearch"/>
    <a-button class="mb8 fr" @click="handleAdd">
      <PlusOutlined/>
      新增
    </a-button>
    <a-table
        :columns="columns"
        :data-source="tableData"
        bordered
        :pagination="pagination"
        @change="handleTableChange"
        :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'operate'">
          <a-button @click="handleEdit(record)" type="link">
            <FormOutlined/>
            编辑
          </a-button>
          <a-button @click="handleDelete(record.id)" type="link">
            <DeleteOutlined/>
            删除
          </a-button>
        </template>
      </template>
    </a-table>
    <a-drawer
        v-model:open="open"
        class="custom-class"
        root-class-name="root-class-name"
        :title="drawTitle"
        placement="right"
        :closable="false"
        width="500"
    >
      <a-form
          ref="formRef"
          :model="formState"
          name="basic"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 15 }"
          autocomplete="off"
          :rules="rules"
      >
        <a-form-item label="数据源名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入数据源名称"/>
        </a-form-item>
        <a-form-item label="描述" name="remark">
          <a-textarea :auto-size="{ minRows: 1, maxRows: 5 }" v-model:value="formState.remark" placeholder="请输入数据源描述"/>
        </a-form-item>
        <a-form-item label="字段" name="fieldIdList">
          <a-select v-model:value="formState.fieldIdList" mode="tags" placeholder="请选择字段" :options="dataFieldOptions">
          </a-select>
        </a-form-item>

      </a-form>
      <template #footer>
        <a-button key="back" style="margin-right: 16px" @click="closeDrawer">取消</a-button>
        <a-button key="submit" type="primary" @click="handleSubmit">提交</a-button>
      </template>
    </a-drawer>
  </div>
</template>